package cn.hdu.community.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @Author zhangxin
 * @Date 2022/4/4
 */

public class JwtTokenUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "hduCommunity";
    private static final String ISS = "hdu";

    // 过期时间是3600秒，既是1个小时
    private static final Long EXPIRATION = 3600L;

    // 选择了记住我之后的过期时间为7天
    private static final Long EXPIRATION_REMEMBER = 604800L;

    // 创建token
    public static String createToken(Integer userId, boolean isRememberMe, String roles) {
        Long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET).claim("roles", roles)
                .setIssuer(ISS)
                .setSubject(String.valueOf(userId))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    /**
     * 解析JWT
     *
     * @param jwtStr
     * @return
     */
    public static Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}

